<template>
  <div class="executions">
    <div class="page-header">
      <h2>执行记录</h2>
    </div>

    <!-- 搜索和筛选 -->
    <el-card style="margin-bottom: 20px;">
      <el-form :model="searchForm" inline>
        <el-form-item label="测试用例">
          <el-input v-model="searchForm.test_case" placeholder="搜索测试用例" clearable />
        </el-form-item>
        <el-form-item label="执行状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待执行" value="pending" />
            <el-option label="执行中" value="running" />
            <el-option label="通过" value="passed" />
            <el-option label="失败" value="failed" />
            <el-option label="错误" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="环境">
          <el-select v-model="searchForm.environment" placeholder="选择环境" clearable>
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadExecutions">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 执行记录列表 -->
    <el-card>
      <el-table :data="executions" v-loading="loading" style="width: 100%">
        <el-table-column prop="test_case_name" label="测试用例" min-width="200" />
        <el-table-column prop="status_display" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="environment_name" label="环境" width="120" />
        <el-table-column prop="execution_time" label="执行时长" width="120">
          <template #default="scope">
            {{ scope.row.execution_time ? `${scope.row.execution_time}s` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_by_username" label="执行者" width="120" />
        <el-table-column prop="created_at" label="执行时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewExecutionResult(scope.row)">查看结果</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="retryExecution(scope.row)"
              :disabled="scope.row.status === 'running'"
            >
              重试
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看执行结果对话框 -->
    <el-dialog v-model="showResultDialog" title="执行结果详情" width="80%">
      <div v-if="selectedExecution">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="测试用例">{{ selectedExecution.test_case_name }}</el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="getStatusType(selectedExecution.status)">
              {{ selectedExecution.status_display }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行环境">{{ selectedExecution.environment_name }}</el-descriptions-item>
          <el-descriptions-item label="执行者">{{ selectedExecution.created_by_username }}</el-descriptions-item>
          <el-descriptions-item label="执行时长">
            {{ selectedExecution.execution_time ? `${selectedExecution.execution_time}s` : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDate(selectedExecution.started_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ formatDate(selectedExecution.finished_at) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;" v-if="selectedExecution.error_message">
          <h4>错误信息</h4>
          <el-alert
            :title="selectedExecution.error_message"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
        
        <div style="margin-top: 20px;" v-if="selectedExecution.result">
          <h4>执行结果</h4>
          <el-input
            v-model="resultJson"
            type="textarea"
            :rows="15"
            readonly
            font-family="monospace"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { executionAPI, environmentAPI } from '@/api'

export default {
  name: 'Executions',
  setup() {
    const loading = ref(false)
    const showResultDialog = ref(false)
    const selectedExecution = ref(null)
    const executions = ref([])
    const environments = ref([])

    const searchForm = reactive({
      test_case: '',
      status: '',
      environment: ''
    })

    const pagination = reactive({
      page: 1,
      page_size: 20,
      total: 0
    })

    const resultJson = computed(() => {
      if (!selectedExecution.value?.result) return ''
      return JSON.stringify(selectedExecution.value.result, null, 2)
    })

    const loadExecutions = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          page_size: pagination.page_size,
          ...searchForm
        }
        const response = await executionAPI.getList(params)
        executions.value = response.results || []
        pagination.total = response.count || 0
      } catch (error) {
        console.error('加载执行记录失败:', error)
      } finally {
        loading.value = false
      }
    }

    const loadEnvironments = async () => {
      try {
        const response = await environmentAPI.getList()
        environments.value = response.results || []
      } catch (error) {
        console.error('加载环境列表失败:', error)
      }
    }

    const resetSearch = () => {
      Object.assign(searchForm, {
        test_case: '',
        status: '',
        environment: ''
      })
      loadExecutions()
    }

    const handleSizeChange = (size) => {
      pagination.page_size = size
      loadExecutions()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      loadExecutions()
    }

    const viewExecutionResult = async (execution) => {
      try {
        const response = await executionAPI.getDetail(execution.id)
        selectedExecution.value = response
        showResultDialog.value = true
      } catch (error) {
        console.error('获取执行结果失败:', error)
      }
    }

    const retryExecution = async (execution) => {
      try {
        const response = await executionAPI.retry(execution.id)
        ElMessage.success('重试执行成功')
        loadExecutions()
      } catch (error) {
        console.error('重试执行失败:', error)
      }
    }

    const getStatusType = (status) => {
      const typeMap = {
        'passed': 'success',
        'failed': 'danger',
        'error': 'danger',
        'running': 'warning',
        'pending': 'info'
      }
      return typeMap[status] || 'info'
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadExecutions()
      loadEnvironments()
    })

    return {
      loading,
      showResultDialog,
      selectedExecution,
      executions,
      environments,
      searchForm,
      pagination,
      resultJson,
      loadExecutions,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      viewExecutionResult,
      retryExecution,
      getStatusType,
      formatDate
    }
  }
}
</script>

<style scoped>
.executions {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 